package com.ugoodtech.mdcc.core.service.impl;

/* Copyright (C) Ugoodtech, Inc - All Rights Reserved.
 * Unauthorized copying of this file, via any medium is strictly prohibited.
 * Proprietary and confidential.
 * Written by Stone Shaw.
 */


import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.ugoodtech.mdcc.core.domain.OpenIdParam;
import com.ugoodtech.mdcc.core.domain.User;
import com.ugoodtech.mdcc.core.dto.MinipAuthRestResponse;
import com.ugoodtech.mdcc.core.repository.OpenIdParamRepository;
import com.ugoodtech.mdcc.core.service.WechatService;
import java.util.List;
import java.util.Objects;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class WechatPushServiceImpl implements WechatService {
    @Value("${wechat.appID}")
    private String appID;
    @Value("${wechat.appSecret}")
    private String appSecret;

    @Value("${wechat.miniAppId}")
    private String miniAppId;
    @Value("${wechat.miniAppSecret}")
    private String miniAppSecret;

    private static final Logger logger = LoggerFactory.getLogger(WechatPushServiceImpl.class);

    @Autowired
    private OpenIdParamRepository openIdParamRepository;

    @Override
    public void pushWechatMessage(User user, String template_id, String directUrl, String first, String remark, String keyword1, String keyword2, String keyword3, String keyword4, String keyword5) {
        try {
            this.pushMessage(
                    user.getOpenId(),
                    template_id,
                    directUrl,
                    first,
                    remark,
                    keyword1, keyword2, keyword3, keyword4, keyword5);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getOpenId(String code) throws Exception {
        System.out.println(appID + "==" + appSecret);
        String weChatUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appID
                + "&secret=" + appSecret + "&grant_type=authorization_code&code=" + code;
        URLConnection urlConnection = null;
        InputStream inputStream = null;
        String body = "";
        try {
            URL url = new URL(weChatUrl);
            urlConnection = url.openConnection();
            urlConnection.setDoOutput(true);
            // 定义待写入数据的内容类型，我们设置为application/x-www-form-urlencoded类型
            urlConnection.setRequestProperty("content-type", "application/json");
            inputStream = urlConnection.getInputStream();
            String encoding = urlConnection.getContentEncoding();
            body = IOUtils.toString(inputStream, encoding);
            JSONObject jsonObject = new JSONObject(body);
            String openId = jsonObject.getString("openid");
            return openId;
        } catch (IOException e) {
            System.out.println(weChatUrl + " 的请求连接失败");
        } catch (JSONException e) {
            System.out.println(weChatUrl + " 的返回json转换失败" + body);
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                System.out.println("请求为" + weChatUrl + "输入流关闭失败");
            }
        }
        //todo
//        return "testOpenId";
        throw new Exception("获取失败");
    }

    @Override
    public String getAccess_token() {
        String access_token = "";
        /////////////////
        OpenIdParam openIdParam = openIdParamRepository.findByOpenId("accessToken");
        if (openIdParam != null) {
            if ((System.currentTimeMillis() - openIdParam.getCreationTime().getTime()) <= 1000 * 60 * 60) {
                String body = openIdParam.getAccessTokenBody();
                access_token = body.split("\"")[3];
                return access_token;
            }
        }else {
            openIdParam = new OpenIdParam();
        }
        /////////////////

        String weChatUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appID + "&secret=" + appSecret;
        URLConnection urlConnection = null;
        InputStream inputStream = null;
        try {
            URL url = new URL(weChatUrl);
            urlConnection = url.openConnection();
            urlConnection.setDoOutput(true);
            // 定义待写入数据的内容类型，我们设置为application/x-www-form-urlencoded类型
            urlConnection.setRequestProperty("content-type", "application/json");
            inputStream = urlConnection.getInputStream();
            String encoding = urlConnection.getContentEncoding();
            String body = IOUtils.toString(inputStream, encoding);

            //////////////////////
            openIdParam.setCreationTime(new Date());
            openIdParam.setAccessTokenBody(body);
            openIdParamRepository.save(openIdParam);
            //////////////////////

            access_token = body.split("\"")[3];
        } catch (IOException e) {
            System.out.println(weChatUrl + " 的请求连接失败");
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                System.out.println("请求为" + weChatUrl + "输入流关闭失败");
            }
        }
        return access_token;
    }


    /**
     * 小程序登录验证
     *
     * @param code
     * @return
     */
    @Override
    public MinipAuthRestResponse miniLoginAuth(String code) {
        MinipAuthRestResponse result = MinipAuthRestResponse.ok(null);
        if (StringUtils.isEmpty(code)) {
            result.setSuccess(false);
            result.setError("请求参数错误");
            return result;
        }
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("grant_type", "authorization_code");
        paramsMap.put("appid", miniAppId);
        paramsMap.put("secret",miniAppSecret);
        paramsMap.put("js_code", code);

        String CODE_2_SESSION = "https://api.weixin.qq.com/sns/jscode2session";
        String body = "";
            body = HttpUtil.get(CODE_2_SESSION, paramsMap);
            logger.info("小程序授权结果 {}.", body);
            cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(body);
            Integer errcode = jsonObject.getInt("errcode");
            if (Objects.isNull(errcode) || 0 == errcode){
                result.setSuccess(true);
                result.setData(jsonObject.getStr("unionid"));
                return result;
            } else {
                result.setSuccess(false);
                result.setError("小程序授权失败");
                return result;
            }

    }


    public boolean pushMessage(String openId, String template_id, String directUrl, String first, String remark, String keyword1, String keyword2, String keyword3, String keyword4, String keyword5) {
        if (StringUtils.isEmpty(openId)) {
            return false;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("touser", openId);
        map.put("template_id", template_id);
        map.put("url", directUrl);
        Map<String, String> miniProg = new HashMap<>();
        miniProg.put("appid", miniAppId);
        miniProg.put("pagepath", "/pages/login/login");
        map.put("miniprogram", miniProg);
        Map<String, Object> dataMap = new HashMap<>();
        Map<String, Object> firstMap = new HashMap<>();
        Map<String, Object> keyword1Map = new HashMap<>();
        Map<String, Object> keyword2Map = new HashMap<>();
        Map<String, Object> keyword3Map = new HashMap<>();
        Map<String, Object> keyword4Map = new HashMap<>();
        Map<String, Object> keyword5Map = new HashMap<>();
        Map<String, Object> remarkMap = new HashMap<>();


//        new SimpleDateFormat(Constants.DEFAULT_DATE_FORMAT).format(new Date());


        firstMap.put("value", first);
        dataMap.put("first", firstMap);

        if (StringUtils.isNotEmpty(keyword1)) {
            keyword1Map.put("value", keyword1);
            dataMap.put("keyword1", keyword1Map);
        }

        if (StringUtils.isNotEmpty(keyword2)) {
            keyword2Map.put("value", keyword2);
            dataMap.put("keyword2", keyword2Map);
        }

        if (StringUtils.isNotEmpty(keyword3)) {
            keyword3Map.put("value", keyword3);
            dataMap.put("keyword3", keyword3Map);
        }

        if (StringUtils.isNotEmpty(keyword4)) {
            keyword4Map.put("value", keyword4);
            dataMap.put("keyword4", keyword4Map);
        }

        if (StringUtils.isNotEmpty(keyword5)) {
            keyword5Map.put("value", keyword5);
            dataMap.put("keyword5", keyword5Map);
        }

        remarkMap.put("value", remark);
        dataMap.put("remark", remarkMap);

        map.put("data", dataMap);
        String accessToken = this.getAccess_token();
//        String accessToken= "14__KShi_uO0T_HYaY2iE0KizErob3blpo6slSzJJk7oeJyfBjthDOE_8F_tkh71PZef8tXkaAeb_H-XYiemy6K5A";

        PrintWriter out = null;
        String weChatUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
        URLConnection urlConnection = null;
        InputStream inputStream = null;
        String body = "";
        try {
            URL url = new URL(weChatUrl);
            urlConnection = url.openConnection();
            // 定义待写入数据的内容类型，我们设置为application/x-www-form-urlencoded类型
            urlConnection.setRequestProperty("content-type", "application/json");
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            out = new PrintWriter(urlConnection.getOutputStream());

            System.out.println(new JSONObject(map).toString());
            out.print(new JSONObject(map).toString());
            out.flush();

            inputStream = urlConnection.getInputStream();
            String encoding = urlConnection.getContentEncoding();
            body = IOUtils.toString(inputStream, encoding);
            logger.info("推送微信结果为[{}].", body);
            JSONObject jsonObject = new JSONObject(body);
            int errcode = jsonObject.getInt("errcode");
            if (0 == errcode) {
                return true;
            } else {
                return false;
            }
        } catch (IOException e) {
            System.out.println(weChatUrl + " 的请求连接失败");
        } catch (JSONException e) {
            System.out.println(weChatUrl + " 的返回json转换失败" + body);
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                System.out.println("请求为" + weChatUrl + "输入流关闭失败");
            }
        }
        return false;
        //todo
//        throw new Exception("获取失败");
    }
}
